﻿using AbstructFactory;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using XF.Meeting.Entity.DTO;
using XF.Meeting.Entity.View;
using UEntity;
using System.Threading;

namespace XF.Common
{
    public class CMSHttpHelper
    {
        private readonly string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36";
        public AbsFactoryTE abs = (AbsFactoryTE)AbsFactory.CreateInterface();
        private static readonly string cmsUrl = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["cmsUrl"]);
        private readonly string apiUser = UCommonWork.Common.Commons.MD5DecodeString(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["apiUser"]));
        private readonly string apipwd = UCommonWork.Common.Commons.MD5DecodeString(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["apipwd"]));
        private HttpWebRequest request = null;
        /// <summary>
        /// 签到之后更新pin码
        /// </summary>
        /// <param name="cinfoId"></param>
        public void SendPasscode(int cinfoId)
        {
            var dal = abs.CreateConferenceRoomInterface("pad", "");
            var res = dal.GetCInfoPwdByID(cinfoId).Result;
            var list = TableToList.ToList<MeetRoomPwd>(res);
            string strError = "";
            foreach (var item in list)
            {
                if (item.cmsGuid != "")
                {
                    LogEntity.Module = "XF.CMSHttpHelper.SendPasscode";
                    LogEntity.OperateObject = "WeChatSignIn";
                    LogEntity.OperateResult = "Success";
                    LogEntity.OperationDescription = $"CInfoId:{cinfoId}--cmsGuid:{item.cmsGuid}--passcode:{item.PWD}。";
                    try
                    {
                        Encoding encoding = Encoding.GetEncoding("utf-8");
                        IDictionary<string, string> parameters = new Dictionary<string, string>();
                        parameters.Add("PassCode", item.PWD);
                        string url = cmsUrl + "coSpaces/" + item.cmsGuid;
                        CMSHttpHelper cMS = new CMSHttpHelper();
                        cMS.PutHttps(url, parameters, encoding);
                    }
                    catch (Exception ex)
                    {

                        LogEntity.OperateResult = "Fail";
                        strError = string.Format("WeChatSignIn Exception:{0}", ex.ToString());

                    }
                    LogEntity.ErrorDescription = strError;
                    RecordLog();

                }
            }
        }
        /// <summary>
        /// 提前结束重置PIN码
        /// </summary>
        /// <param name="cinfoId"></param>
        public void ResetPasscode(int cinfoId)
        {
            var strError = "";
            var dal = abs.CreateConferenceRoomInterface("pad", "");
            var res = dal.GetCInfoPwdByID(cinfoId).Result;
            var list = TableToList.ToList<MeetRoomPwd>(res);
            foreach (var item in list)
            {
                if (item.cmsGuid != ""&&item.IsSignIn)
                {
                    try
                    {
                        LogEntity.Module = "XF.CMSHttpHelper.ResetPasscode";
                        LogEntity.OperateObject = "ResetPasscode";
                        LogEntity.OperateResult = "Success";
                        LogEntity.OperationDescription = $"CInfoId:{cinfoId}--cmsGuid:{item.cmsGuid}--passcode:{item.PWD}。";
                        Encoding encoding = Encoding.GetEncoding("utf-8");
                        IDictionary<string, string> parameters = new Dictionary<string, string>();
                        parameters.Add("PassCode", item.PassCode);
                        string url = cmsUrl + "coSpaces/" + item.cmsGuid;
                        PutHttps(url, parameters, encoding);
                    }
                    catch (Exception ex)
                    {

                        LogEntity.OperateResult = "Fail";
                        strError = string.Format("ResetPasscode Exception:{0}", ex.ToString());

                    }
                    LogEntity.ErrorDescription = strError;
                    RecordLog();

                }
            }
        }
        private UEntity.LogEntity.ELogRecordEntity LogEntity = new UEntity.LogEntity.ELogRecordEntity();
        /// <summary>
        /// 重置所有会议室pin码
        /// </summary>
        /// <param name="item"></param>
        /// <param name="strError"></param>
        public void SetPassCode(CRoomInfo item, out string strError)
        {
            LogEntity.Module = "XF.Meeting.Service.MeetingService.UpdateMeetingRoomByID";
            LogEntity.OperateObject = "UpdatePasscode";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = $"RoomId:{item.ID}--cmsGuid:{item.CMSGuid}--passcode:{item.passcode}。";
            var bResult = true;
            strError = "";
            if (item.CMSGuid != "")
            {
                try
                {
                    Encoding encoding = Encoding.GetEncoding("utf-8");
                    IDictionary<string, string> parameters = new Dictionary<string, string>();
                    parameters.Add("PassCode", item.passcode);
                    string url = cmsUrl + "coSpaces/" + item.CMSGuid;
                    PutHttps(url, parameters, encoding);

                    if (!bResult)
                    {
                        LogEntity.OperateResult = "Fail";
                        bResult = false;
                    }
                }
                catch (Exception ex)
                {
                    bResult = false;
                    LogEntity.OperateResult = "Fail";
                    strError = string.Format("UpdatePasscode Exception:{0}", ex.ToString());

                }
                LogEntity.ErrorDescription = strError;
                RecordLog();

            }
        }
        private void RecordLog()
        {
            LogEntity.Operator = apiUser;
            LogEntity.OperateIP = apipwd;
            ULogWork.CLogToDataBase.RecordOperateLog(LogEntity);
        }
        private void PutHttps(string url, IDictionary<string, string> parameters, Encoding charset)
        {

            CookieContainer cookie = new CookieContainer();
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            //HTTPSQ请求
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            if (request == null)
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                request.CookieContainer = cookie;
                request.ProtocolVersion = HttpVersion.Version11;
                request.Method = "Put";
                string base64EncodedAuthorizationString = apiUser + ":" + apipwd;
                byte[] binaryData = new Byte[base64EncodedAuthorizationString.Length];
                binaryData = Encoding.UTF8.GetBytes(base64EncodedAuthorizationString);
                base64EncodedAuthorizationString = Convert.ToBase64String(binaryData);
                base64EncodedAuthorizationString = "Basic " +
             base64EncodedAuthorizationString;
                request.Headers["Authorization"] = base64EncodedAuthorizationString;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = DefaultUserAgent;
                request.KeepAlive = false;
                request.Headers["Accept-Language"] = "zh-CN,zh;q=0.9";
            }
            // request.Headers["Cookie"] = "username=aaaaaa; Language=zh_CN";
            //  如果需要POST数据
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, WebUtility.UrlEncode(parameters[key]));
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, WebUtility.UrlEncode(parameters[key]));
                    }
                    i++;
                }
                byte[] data = charset.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }

            request.GetResponse();
            request.Abort();
        }
        private CMSEntity GetHttps(string url, IDictionary<string, string> parameters, Encoding charset)
        {

            CookieContainer cookie = new CookieContainer();
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            //HTTPSQ请求
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            if (request == null)
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                request.CookieContainer = cookie;
                request.ProtocolVersion = HttpVersion.Version11;
                request.Method = "Get";
                string base64EncodedAuthorizationString = apiUser + ":" + apipwd;
                byte[] binaryData = new Byte[base64EncodedAuthorizationString.Length];
                binaryData = Encoding.UTF8.GetBytes(base64EncodedAuthorizationString);
                base64EncodedAuthorizationString = Convert.ToBase64String(binaryData);
                base64EncodedAuthorizationString = "Basic " +
             base64EncodedAuthorizationString;
                request.Headers["Authorization"] = base64EncodedAuthorizationString;
              request.ContentType = "application/xml";
                request.UserAgent = DefaultUserAgent;
                request.KeepAlive = false;
                request.Accept= "*/*";
                //request.Headers["Accept-Language"] = "zh-CN,zh;q=0.9";
            }
            // request.Headers["Cookie"] = "username=aaaaaa; Language=zh_CN";
            //  如果需要POST数据
            var response = (HttpWebResponse)request.GetResponse();
            
            var xml = new CMSEntity();
            
           var stream = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                var retString = reader.ReadToEnd();
           
                  xml = TableToList.XMLDeSerialize<CMSEntity>(retString);
                //    Console.WriteLine($"{xml.passcode}");
            }
         

          // xml= TableToList.XMLDeSerialize<CMSEntity>(content);


         
            //stream.Close();
            request.Abort();
            //response.Close();
            return xml;
        }
        public void ResetPasscodeAdd(string passCode)
        {
            //Encoding encoding = Encoding.GetEncoding("utf-8");
            //IDictionary<string, string> parameters = new Dictionary<string, string>();
            //parameters.Add("PassCode", passCode);
            //string url = cmsUrl + "coSpaces/" + item.cmsGuid;
            //HttpWebResponse response = PutHttps(url, parameters, encoding);
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受   
        }

        public MeetRooMPIN  GetPassCode(MeetRooMPIN item,  out string strError)
        {
            strError = "";
                if (item.cmsGuid != "")
                {
                    LogEntity.Module = "XF.CMSHttpHelper.GetPassCode";
                    LogEntity.OperateObject = "GetPassCode";
                    LogEntity.OperateResult = "Success";
                  LogEntity.OperationDescription = $"CRoomID:{item.CRoomID}--cmsGuid:{item.cmsGuid}。";
                    try
                    {
                        Encoding encoding = Encoding.GetEncoding("utf-8");
                        IDictionary<string, string> parameters = new Dictionary<string, string>();
                        string url = cmsUrl + "coSpaces/" + item.cmsGuid;
                        var xml = GetHttps(url, parameters, encoding);
                  
                    item.Passcode = xml.passcode;
                        LogEntity.OperationDescription = $"CRoomID:{item.CRoomID}--cmsGuid:{item.cmsGuid}--passcode:{item.Passcode}。";
                    }
                    catch (Exception ex)
                    {

                        LogEntity.OperateResult = "Fail";
                        strError = string.Format("GetPassCode Exception:{0}", ex.ToString());

                    }
                    LogEntity.ErrorDescription = strError;
                    RecordLog();
                  
                }
            return item;
      
        }
    }
}
